package com.cn.wanxi.util;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.List;

public class UpLoad {
    public String imgUpload(HttpServletRequest req) {
            String savePath = "F:\\wanxi\\gongzuo\\huanbao\\seven\\hunbao07before-0901\\web";//保存图片的路径（具体的根目录）
            String imgPath = "/loadImg/";//文件前的路径
            File file = new File(savePath + imgPath);//创建一个目录
            if (!file.exists() && !file.isDirectory()) {
                System.out.println(savePath + "目标目录不存在，需要创建");
                file.mkdir();//创建
            }
            StringBuilder stringBuilder = new StringBuilder();
            try {
            //1.创建DiskFileItemFactory工厂
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //2.创建一个文件解析器
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setHeaderEncoding("UTF-8");
            //判断提交上来的数据是不是一个表单数据
            if (!ServletFileUpload.isMultipartContent(req)) {
                return "";
            }
            //4. 使用ServletFileUpload解析器来解析上传数据，解析器返回的是一个 List<FileItem> 集合，每一个FileItem对应一个form表单
            List<FileItem> list = upload.parseRequest(req);
            for (FileItem item : list) {
                //判断内容是否为普通表单属性
                if (item.isFormField()) {
                    String name = item.getFieldName();
                    String value = item.getString("UTF-8");
                    System.out.println(name + "=" + value);
                    stringBuilder.append(value + "@@");
                }else {
                    String filename = item.getName();
                    System.out.println(filename);
                    if (filename == null || filename.trim().equals("")){
                        continue;
                        //跳出当前循环
                        //break;//跳出所有
                        //return;//跳出方法
                    }
                    filename = filename.substring(filename.lastIndexOf("\\") + 1);
                    //获取item输入流
                    InputStream inputStream = item.getInputStream();
                    String href = imgPath + filename;//数据库保存的路径
                    String imgurl = savePath + href;//图片存储路径
//                    if (href.equals("")){
//                        href="0";
//                    }
                    stringBuilder.append(href+"@@");

                    FileOutputStream fileOutputStream = new FileOutputStream(imgurl);
                    //创建一个缓冲区
                    byte buffer[] = new byte[1024];
                    //判断输入流是否已读完的标志
                    int len = 0;
                    while((len = inputStream.read(buffer))>0){
                        fileOutputStream.write(buffer,0,len);
                    }
                    inputStream.close();
                    fileOutputStream.close();
                    item.delete();
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }
}
